//
//  LoginViewController.m
//  FyApp
//
//  Created by user on 15/10/10.
//  Copyright © 2015年 user. All rights reserved.
//

#import "LoginViewController.h"
#import "RegistViewController.h"
#import "ForgetPwdViewController.h"

@interface LoginViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UITableView  *loginTab;
@property(nonatomic,strong)UIButton     *loginBtn;
@property(nonatomic,strong)UIButton     *registerBtn;
@property(nonatomic,strong)UIButton     *forgetBtn;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTheNavigationBar];
    [self createUI];
}

#pragma mark -------------创建导航栏及相关控件
-(void)createTheNavigationBar
{
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"登录"];
    [self.view addSubview:topView];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 35.0f, 49.0f, 16.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    backBtn.hidden = self.backBtHide;
    [topView addSubview:backBtn];
    [topView addSubview:self.registerBtn];
}

- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self dismissViewControllerAnimated:TRUE completion:^(void){}];
}
-(void)createUI
{
    //    分割线
    
    UILabel *sepLab1 = [[UILabel alloc] initWithFrame:CGRectMake(8.0f, 16.0f+50.0f, SCREEN_WIDTH-16.0f, .5f)];
    sepLab1.backgroundColor = [UIColor hexStringToColor:kColorGraySperator];
    
    
    [self.loginTab addSubview:sepLab1];
    
    
    [self.view addSubview:self.loginTab];
    [self.loginTab addSubview:self.loginBtn];
//    [self.loginTab addSubview:self.registerBtn];
    [self.loginTab addSubview:self.forgetBtn];
}

//表
-(UITableView *)loginTab
{
    if (!_loginTab) {
        _loginTab = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _loginTab.delegate = self;
        _loginTab.dataSource = self;
        
        _loginTab.rowHeight = 50.0f;
        _loginTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _loginTab;
}

//登录按钮
-(UIButton *)loginBtn
{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(16.0f, self.forgetBtn.frame.origin.y+self.forgetBtn.frame.size.height+16.0f, SCREEN_WIDTH - 32.0f, 44.0f)];
        [_loginBtn addTarget:self action:@selector(buttonLoginTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        _loginBtn.layer.cornerRadius = 2;
        _loginBtn.layer.masksToBounds = YES;
        [_loginBtn setBackgroundColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
    }
    return _loginBtn;
}
//注册按钮
-(UIButton *)registerBtn
{
    if (!_registerBtn) {
        _registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-16.0f-44.0f, 23.0f, 44.0f, 44.0f)];
        [_registerBtn addTarget:self action:@selector(buttonRegistTapped:) forControlEvents:UIControlEventTouchUpInside];
        
        [_registerBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
//        [_registerBtn setTitleColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
        
        [_registerBtn.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    }
    return _registerBtn;
}
//忘记按钮
-(UIButton *)forgetBtn
{
    if (!_forgetBtn) {
        _forgetBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-80.0f, 120.0f, 72.0f, 36.0f)];
        [_forgetBtn addTarget:self action:@selector(buttonForgetTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
        [_forgetBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_forgetBtn.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
        [_forgetBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        
    }
    return _forgetBtn;
}

#pragma mark-tableViewDelegate&datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

static UITextField *__textField;//记录当前的textField
static UITextField *__textFieldPwd;//记录当前的textField
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel*lab = [[UILabel alloc]initWithFrame:CGRectMake(16.0f, 13.0f, 50.0f, 24.0f)];
        lab.tag = 1000;
        lab.font = [UIFont systemFontOfSize:14.0f];
        [cell.contentView addSubview:lab];
        
        
        UITextField *userTF = [[UITextField alloc] initWithFrame:CGRectMake(72.0f, 5.0f, SCREEN_WIDTH - 88.0f, 45.0f)];
        userTF.tag = 2000;
        userTF.delegate = self;
        userTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        userTF.font = [UIFont systemFontOfSize:14.0f];
        userTF.borderStyle = UITextBorderStyleNone;
        [cell.contentView addSubview:userTF];
        
        
    }
    
    UILabel *imgView = (UILabel*)[cell.contentView viewWithTag:1000];
    UITextField *text = (UITextField *)[cell.contentView viewWithTag:2000];
    
    
    
    if (indexPath.row==0) {
        
        imgView.text = @"账号";
        text.placeholder = @"请输入手机号";
        text.keyboardType = UIKeyboardTypeNumberPad;
        __textField = text;
    }
    if (indexPath.row==1) {
        imgView.text = @"密码";
        text.placeholder = @"请输入登录密码";
        __textFieldPwd = text;
        text.secureTextEntry = YES;
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16.0f;
}

#pragma mark-忘记按钮方法
-(void)buttonForgetTapped:(id)sender
{
    ForgetPwdViewController *forgetPswVC = [[ForgetPwdViewController alloc]init];
    [self presentViewController:forgetPswVC animated:TRUE completion:^(void){}];
}

#pragma mark-登录按钮方法
-(void)buttonLoginTapped:(id)sender
{
    [self.view endEditing:YES];
    
    BOOL isPhone = [AccountTools validatePhoneNumber:__textField.text];

    if (__textField.text.length==0) {
        ALERT_VIEW(@"请输入手机号");
    }
    else if (__textFieldPwd.text.length==0)
    {
        ALERT_VIEW(@"请输入密码");
        
    }
    else if (isPhone == NO)
    {
        ALERT_VIEW(@"请输入正确的手机号");
    }
    else {
        //        发请求
        NSString *PSWStr = [NSString stringWithFormat:@"%@%@",__textField.text,__textFieldPwd.text];
        NSString *threePSWStr = [AccountTools md5:[AccountTools md5:[AccountTools md5:PSWStr]]] ;
        
        [[AnimationIndicator sharedIndicator] startAnimation];
        [AppGlobalClass PostDataWithNSstring:LOGIN_URL withDictionary:@{@"userCd":__textField.text,@"password":threePSWStr} success:^(NSDictionary *dictionary) {
            
            
            if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                NSDictionary *dict = [listArray firstObject];
                // 存取用户信息
                [AccountTools saveUserToken:[dict objectForKey:@"token"]];
                [AccountTools Saveid:[dict objectForKey:@"userId"] userHeadPhoto:[dict objectForKey:@"userHeadPhoto"]];
                [AccountTools saveUserCd:[dict objectForKey:@"userCd"]];
                [self dismissViewControllerAnimated:TRUE completion:^(void){}];
                ALERT_VIEW(@"登录成功");

                
            }else
            {
                NSString * str = [dictionary objectForKey:@"message"];
                
                ALERT_VIEW(str);
                
            }
            [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"完成" withType:TRUE];
            
        } failure:^(NSError *error) {
            
            [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"失败" withType:TRUE];
        } networkerror:^(NSString *networkerror) {
            
            [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"无网络" withType:TRUE];
        }];
        
    }
    
    
    
}


#pragma mark-注册按钮方法
- (void)buttonRegistTapped:(id)sender
{
    RegistViewController *registerVC = [[RegistViewController alloc]init];
    [self presentViewController:registerVC animated:TRUE completion:^(void){}];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
